<template>
<div class="app-container">

    <el-form ref="form" :rules="rules" class="thin-form" :model="form" label-width="120px">

        <el-form-item label="姓名" prop="name" required>
            <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="职位" prop="title" required>
            <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="站点" prop="site" required>
            <el-select v-model="form.site" placeholder="选择站点" :disabled="true">
                <el-option v-for="item in sites" :key="item._id" :label="item.name" :value="item._id">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="经验" prop="experience">
            <el-input v-model="form.experience"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="intro" required>
            <el-input v-model="form.intro"></el-input>
        </el-form-item>
        <el-form-item label="头像" >
            <el-button @click="toggleShow">设置头像</el-button>
            <!-- <a class="btn" @click="toggleShow"></a> -->
        	<my-upload field="img"
                @crop-success="cropSuccess"
                @crop-upload-success="cropUploadSuccess"
                @crop-upload-fail="cropUploadFail"
                v-model="show"
        		:width="800"
        		:height="600"
                :noRotate="false"
                :maxSize="10240"
        		img-format="jpg"></my-upload>
        	<img class="preview" :src="imgDataUrl">
            <!-- <el-button @click="onReset">上传图片</el-button>
            <input class="headimg" type="file" v-on:change="uploadFile($event)" /> -->
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="onReset">重置</el-button>
        </el-form-item>
    </el-form>

</div>
</template>

<script>
import fetch from '@/utils/fetch';
import {
    parseTime
} from '@/utils';
import industries from '@/data/industries.json';
import ElButton from "../../../../node_modules/element-ui/packages/button/src/button";
import { mapGetters } from 'vuex';
// import 'babel-polyfill'; // es6 shim
import Vue from 'vue';
import myUpload from 'vue-image-crop-upload';

export default {
    components: {
        ElButton,
        'my-upload': myUpload
    },
    data() {
        return {
            form: {
                title: '',
                name: '',
                site: '',
                city: '',
                phone: '',
                intro: '',
                image: '',
            },
            sites: {},
            rules: {
                title: {
                    required: true,
                    message: '请输入职位',
                    trigger: 'blur'
                },
                name: {
                    required: true,
                    message: '请输入姓名',
                    trigger: 'blur'
                },
                site: {
                    required: true,
                    message: '请选择站点',
                    trigger: 'blur'
                },
                intro: {
                    required: true,
                    message: '请输入简介',
                    trigger: 'blur'
                },
            },
            isNew: true,
            show: false,
            imgDataUrl: ''
        }
    },
    watch: {

    },
    created() {
        if (this.$route.params.id) {
            this.isNew = false;
            this.fetchData();
        }
        this.fetchSitesData();
    },
    computed: {
        ...mapGetters([
          'site',
          'city'
        ]),
    },
    methods: {
        toggleShow() {
            this.show = !this.show;
        },
        /**
			 * crop success
			 *
			 * [param] imgDataUrl
			 * [param] field
			 */
			cropSuccess(imgDataUrl, field){
				console.log('-------- crop success --------');
                this.imgDataUrl = imgDataUrl;
				this.form.image = imgDataUrl;
			},
			/**
			 * upload success
			 *
			 * [param] jsonData   服务器返回数据，已进行json转码
			 * [param] field
			 */
			cropUploadSuccess(jsonData, field){
				console.log('-------- upload success --------');
				console.log(jsonData);
				console.log('field: ' + field);
			},
			/**
			 * upload fail
			 *
			 * [param] status    server api return error status, like 500
			 * [param] field
			 */
			cropUploadFail(status, field){
				console.log('-------- upload fail --------');
				console.log(status);
				console.log('field: ' + field);
			},



        fetchData() {
            fetch({
                url: '/staff/' + this.$route.params.id,
                method: 'get'
            }).then(res => {
                console.log(res)
                Object.assign(this.form, res.data);
                this.form.site = this.site;
                this.imgDataUrl = res.data.image;
                console.log(this.form.site.$id)
            })

        },
        fetchSitesData() {
            fetch({
                url: '/sites',
                method: 'get'
            }).then(res => {
                this.form.site = this.site;
                console.log(this.site)
                this.sites = res.data;
            })
        },
        onReset() {
            this.$refs.form.resetFields();
        },
        onSubmit() {

            this.$refs.form.validate((valid) => {
                if (valid) {
                    fetch({
                        url: '/staff' + (this.isNew ? '' : '/' + this.$route.params.id),
                        method: this.isNew ? 'post' : 'put',
                        data: JSON.parse(JSON.stringify(this.form))
                    }).then(res => {
                        if (res.data.ok === 1) {
                            this.$message('保存成功');
                            this.$router.push('/member/staffs');
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        uploadFile($event) {
            var me = this;
            console.log($event.target.files)
            var file = $event.target.files[0];
            console.log(file);
            var size = file.size / 1024000;
            if ( size > 1 ) {
                alert('图像太大');
            } else {
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onloadend = function() {
                    var dataUrl = reader.result;
                    console.log(me)
                    me.form.img = dataUrl;
                    // console.log(dataUrl);
                }
            }

        }


    },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.checkbox-item {
    display: block;
    margin: 6px 20px 6px 10px;
}
.img {
    margin: 8px 0;
    width: 80px;
    height: 60px;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    &[lazy=error],
    &[lazy=loading] {
        background-size: 50%;
    }
}
.time {
    word-break: break-all;
}
.search-input {
    width: 300px;
}
.headimg {
    opacity: 0;
    position: relative;
    left: -92px;
    top: -10px;
    width: 88px;
    height: 36px;
    cursor: pointer;
}
.preview {
    max-width: 400px;
    max-height: 300px;
}
</style>
